local fk__jingzhu = fk.CreateSkill {

  name = "fk__jingzhu",

  tags = { Skill.Compulsory, },

}

local U = require "packages/utility/utility"


fk__jingzhu:addEffect(fk.CardUseFinished, {
  name = "fk__jingzhu",
  anim_type = "control",
  derived_piles = "fk__jingzhu",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(fk__jingzhu.name) and U.isPureCard(data.card)
    and data.tos and table.contains(data:getAllTargets(), player)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local all_choices = {"#fk__jingzhu_put:::"..data.card.name,"#fk__jingzhu_watch"}
    local choices = {}
    if room:getCardArea(data.card) == Card.Processing or table.contains(player:getCardIds("e"), data.card:getEffectiveId()) then
      table.insert(choices, all_choices[1])
    end
    local targets = table.filter(room.alive_players, function (p)
      return player ~= p and not p:isKongcheng()
    end)
    if #targets > 0 and #player:getPile(fk__jingzhu.name) > 0 then
      table.insert(choices, all_choices[2])
    end
    if #choices == 0 then return end
    local choice = room:askForChoice(player, choices, fk__jingzhu.name, nil, false, all_choices)
    if choice == all_choices[1] then
      player:addToPile(fk__jingzhu.name, data.card, true, fk__jingzhu.name)
    else
      local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#fk__jingzhu-choose", fk__jingzhu.name, false)
      local to = room:getPlayerById(tos[1])
      local result = room:askForPoxi(player, "fk__jingzhu", {
        { fk__jingzhu.name, player:getPile(fk__jingzhu.name) },
        { to.general, to:getCardIds("h") },
      }, nil, true)
      if #result == 2 then
        room:moveCards({
          ids = {result[1]},
          from = player,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonPutIntoDiscardPile,
          skillName = fk__jingzhu.name,
          proposer = player,
        })
        local cid = result[2]
        if not player.dead and table.contains(to:getCardIds("h"), cid) then
          room:askForUseRealCard(player, {cid}, fk__jingzhu.name, "#fk__jingzhu-use:::"..Fk:getCardById(cid):toLogString(),
          {expand_pile = {cid}}, false, false)
        end
      end
    end
  end,
})

return fk__jingzhu